package com.ly.mpayment.core.util;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.ly.mpayment.persist.hibernate.Page;

/**
 * 分页工具
 *
 */
public class PaginationUtil {
	/**
	 * hql 分页
	 * @param sql
	 * @param Page
	 * @return
	 */
	public static Page queryPagination(String hql, Page Page,Session session) {
		if (Page == null) {
			Page = new Page();
		}
		Integer pageNumber = Page.getStart();
		Integer pageSize = Page.getPageSize();
		String countHql = "select count(*) " + hql.substring(hql.indexOf("from"));
		Query query = session.createQuery(countHql);
		int totalRecord = Integer.valueOf(query.uniqueResult() + "");
		query = session.createQuery(hql);

		query.setFirstResult(pageSize * (pageNumber - 1));
		query.setMaxResults(pageSize);
		List list = query.list();
		Page.setPageSize(pageSize);
		Page.setTotalCount(totalRecord);
		Page.setResult(list);
		session.close();
		return Page;
	}

	public static Page queryPaginationNotCount(String hql, Page Page,Session session) {
		if (Page == null) {
			Page = new Page();
		}
		Integer pageNumber = Page.getStart();
		Integer pageSize = Page.getPageSize();
		Query query = session.createQuery(hql);
		query.setFirstResult( pageSize * (Page.getStart() - 1));
		query.setMaxResults(pageSize);
		List list = query.list();
		Page.setResult(list);
		session.close();
		return Page;
	}


	public static Page queryPaginationNotCountSQL(String sql, Page Page,Session session) {
		if (Page == null) {
			Page = new Page();
		}
		Integer pageNumber = Page.getStart();
		Integer pageSize = Page.getPageSize();

		Query query = session.createSQLQuery(sql);

		query.setFirstResult(pageSize * (pageNumber - 1));
		query.setMaxResults(pageSize);
		List list = query.list();
		Page.setPageSize(pageSize);
		Page.setTotalCount(0);
		Page.setResult(list);
//		session.close();
		return Page;
	}
	/**
	 * sql 分页
	 * @param sql
	 * @param Page
	 * @return
	 */
	public static Page queryPaginationSQL(String sql, Page Page,Session session) {
		if (Page == null) {
			Page = new Page();
		}
		Integer pageNumber = Page.getStart();
		Integer pageSize = Page.getPageSize();
		String countHql = "select count(*) " + sql.substring(sql.indexOf("from"));

		Query query = session.createSQLQuery(countHql);
		int totalRecord = Integer.valueOf(query.uniqueResult() == null ? "0" : query.uniqueResult() + "");
		query = session.createSQLQuery(sql);

		query.setFirstResult(pageSize * (pageNumber - 1));
		query.setMaxResults(pageSize);
		List list = query.list();
		Page.setPageSize(pageSize);
		Page.setTotalCount(totalRecord);
		Page.setResult(list);
//		session.close();
		return Page;
	}

	/**
	 *
	 */
	public static Page getPage(int pageSize,int pageNum){
		Page Page = new Page();
		Page.setPageSize(pageSize);
		Page.setStart(pageNum);
		return Page;
	}
}
